Is there a regex syntax equivalent to "must contain a character outside of this given range"?
For instance, if I want to match any string that contains a character which is not any of these: 1,a,@
...but can also contain the characters in the range?
Examples:
1111 - Would not match
11a@ - Would not match
1a@b - Would match
cdef - Would match
I thought perhaps (?=.*[^1a@]) would do the trick, but no dice.
Instead of using a lookahead, you could match at least a single occurrence of [^1a@] in the string.
Note that [^1a@] can also match a newline or a space.
^.*?[^1a@\r\n].*$
See a regex demo.
If you don't want to match only spaces, you use \s in the negated character class [^1a@\s] to exclude a whitspace char only being a valid match.
Example getting the whole match:
const regex = /^.*?[^1a@\r\n].*$/;
["1111", "11a@", "1a@b", "cdef"].forEach(s => {
const m = s.match(regex);
if (m) {
console.log(s)
}
});
Example testing if the string contains any char other than the listed in the character class:
["1111", "11a@", "1a@b", "cdef"].forEach((s) => {
if (/[^1a@]/.test(s)) {
console.log(s);
}
});